package com.bawei.mall.user.controller;

import com.alibaba.fastjson2.JSON;
import com.bawei.common.core.domain.R;
import com.bawei.common.core.utils.JwtUtils;
import com.bawei.common.security.utils.SecurityUtils;
import com.bawei.mall.user.domain.Address;
import com.bawei.mall.user.domain.CusUser;
import com.bawei.mall.user.service.AddressService;
import com.bawei.mall.user.util.AddrUtils;
import com.bawei.system.domain.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService addressService;
    @Autowired
    private AddrUtils addr;
    @Autowired
    private StringRedisTemplate redisTemplate;
    private static final String ACCESS_TOKEN="login_tokens:";
    /**
     * 展示地址
     */
    @PostMapping("/findAllAddress")
    public R<List<Address>> findAllAddress(){
        List<Address> list = addressService.findAllAddress();
        return R.ok(list);
    }


    /**
     * 获取地址 自动写入
     */
    @GetMapping("/getAddress")
    public R getAddress(@RequestParam("address") String address){
        String s = addr.pathAddres(address);
        Map map = JSON.parseObject(s, Map.class);
        return R.ok(map.get("data"));

    }


    /**
     * 添加地址解析
     */
    @PostMapping("/add")
    public R addResolution(@RequestBody Address address){

        //调用SecurityUtils
        String token = SecurityUtils.getToken();
        String key = JwtUtils.getUserKey(token);
        String userKey=getTokenKey(key);
        String s = redisTemplate.opsForValue().get(userKey);
        LoginUser loginUser = JSON.parseObject(s, LoginUser.class);
        CusUser cusUser = loginUser.getCusUser();
        address.setUserId(Integer.valueOf(String.valueOf(cusUser.getUserId())));
        addressService.addDetil(address);
        return R.ok();
    }

    /**
     * 获取key
     * @param key
     * @return
     */
    private String getTokenKey(String key) {
        return ACCESS_TOKEN + key;
    }

    @GetMapping("/findById")
    public R findById(@RequestParam Integer id){
        Address byId = addressService.findById(id);
        return R.ok(byId);
    }


    @GetMapping("/updateAddress")
    public R updateAddress(@RequestBody Address address){
        addressService.updateAddress(address);
        return R.ok();
    }

    @GetMapping("/delAddress")
    public R  showAddress(@RequestParam Integer id){
        addressService.showAddress(id);
        return R.ok();
    }












}
